package com.zhkj.txg.module.product.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.widget.ImageView
import androidx.lifecycle.Observer
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.txg.R
import com.zhkj.txg.module.product.vm.ShareViewModel
import com.zhkj.txg.widget.watcher.GlideSimpleLoader
import com.zhkj.txg.widget.watcher.ImageWatcher
import kotlinx.android.synthetic.main.activity_watcher.*

/**
 * 图片查看
 */
class WatcherActivity : ViewModelActivity<ShareViewModel>() {
    companion object {
        private val LIST = "list"
        private val INDEX = "index"
        fun open(activity: Activity, list: ArrayList<String>, index: Int) {
            val intent = Intent(activity, WatcherActivity::class.java).putExtra(INDEX, index)
                .putStringArrayListExtra(LIST, list)
            activity.startActivity(intent)
        }
    }

    override val layoutResId: Int = R.layout.activity_watcher

    override fun setViewModel(): ShareViewModel = createViewModel()

    override fun initUI() {
        with(watcher) {
            setLoader(GlideSimpleLoader())
            setDetachAffirmative()
            setTranslucentStatus(0)
            setErrorImageRes(R.drawable.ic_logo)
            setOnStateChangedListener(object : ImageWatcher.OnStateChangedListener {
                override fun onStateChangeUpdate(
                    imageWatcher: ImageWatcher,
                    clicked: ImageView,
                    position: Int,
                    uri: Uri,
                    animatedValue: Float,
                    actionTag: Int
                ) = Unit

                override fun onStateChanged(
                    imageWatcher: ImageWatcher,
                    position: Int,
                    uri: Uri,
                    actionTag: Int
                ) {
                    if (actionTag == ImageWatcher.STATE_EXIT_HIDING) finish()
                }
            })
        }

        tvSavePPicture.setOnClickListener {
            requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, {
                val string = intent.getStringArrayListExtra(LIST)[watcher.currentPosition]
                viewModel.savePicture(this, listOf(string))
            }, {
                toast(getString(R.string.read_permission_deny))
            })
        }
    }

    override fun initViewModel() {
        viewModel.savePictureLiveData.observe(this, Observer {
            toast(getString(R.string.save_picture_success))
        })
    }

    override fun initData() {
        val index = intent.getIntExtra(INDEX, 0)
        val list = intent.getStringArrayListExtra(LIST)
        list?.let { urls ->
            val uris = mutableListOf<Uri>()
            urls.forEach { uris.add(Uri.parse(it)) }
            watcher.show(uris, index)
        }
    }

    override fun onBackPressed() {
        if (watcher.handleBackPressed()) super.onBackPressed()
    }
}